/* Singleton.h
Copyright (c) 2009 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Header file for the Singleton template, which allows you to convert any class
(e.g. a class named "One") into a singleton just by adding to its declaration:

class One : public Singleton<One>

You do not need to make One's constructor private, make Singleton<One> a friend
of One, or do anything of that sort. The trick is that the singleton constraint
is enforced, not by a private constructor, but by making Singleton an abstract
class.

The Singleton template also makes all singleton classes non-copyable.

This class is not thread-safe: it does not keep multiple threads from using (or
even creating) the singleton instance at the same time.
*/

#ifndef __MZ_SINGLETON_H__
#define __MZ_SINGLETON_H__

#include "Noncopyable.h"

#include <memory>

using std::auto_ptr;



template <class Type>
class Singleton : public Noncopyable {
public:
	virtual ~Singleton() {}
	
	// Get the one and only instance of class Type.
	static Type &GetInstance()
	{
		static auto_ptr<Instance> instance;

		if(!instance.get())
			instance.reset(new Instance);

		return *instance;
	}


private:
	// Make all classes derived from Singleton abstract, unless they define
	// this function.
	virtual void SingletonCannotBeInstantiated() = 0;

	// Create a non-abstract class derived from Type.
	class Instance : public Type {
	private:
		virtual void SingletonCannotBeInstantiated() {}
	};
};



#endif
/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */

